#include <iostream>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};




ListNode *detectCycle(ListNode *head) {

    ListNode* dummy = new ListNode(-1);
    dummy->next = head;
    ListNode* s = dummy;
    ListNode* f = dummy;
    while(f && f->next){
        s = s->next;
        f = f->next->next;
        if(s == f){
            break;
        }
    }
    if(f == nullptr || f->next == nullptr) {
        return nullptr;
    }
    f = dummy;
    while(true){
        f = f->next;
        s = s->next;
        if(s == f) return s;
    }
}